﻿/*
 * Autore: Paolo Farina
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using RecipesManager.Data;
using RecipesManager.Data.Operations;
using RecipesManager.MainControls.GenericUserControls;
using RecipesManager.MainControls.ShopSubControls;

namespace RecipesManager.MainControls
{
    /// <summary>
    /// Logica di interazione per ShopUserControl.xaml
    /// </summary>
    public partial class ShopUserControl : UserControl,IMyUserControls, ISwitchable
    {
        ShopMainPane _actualPanel;
        readonly LeftSideListUserControl _leftList;
        readonly ListBox lb_items;
        readonly TextBox tb_search;
        readonly Button bt_cancella;


        public string SectionName { get { return (string)Application.Current.FindResource("ShopsSectionLabel"); } }

        public ShopUserControl()
        {
            InitializeComponent();
            _leftList = new LeftSideListUserControl { UsedBy = this };

            leftSideList.Content = _leftList;
            lb_items = _leftList.lb_items;
            tb_search = _leftList.tb_search;
            bt_cancella = _leftList.bt_delete;

            Refresh_Shop_List();
            CommandManager.RegisterClassCommandBinding(typeof(ShopUserControl), _savebinding);
            CommandManager.RegisterClassCommandBinding(typeof(ShopUserControl), _closebinding);
            
        }

        private void Refresh_Shop_List(string id="")
        {
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            lb_items.SelectedItem = null;
            var count = lb_items.Items.Count;
            for (int i = 0; i < count; i++) lb_items.Items.RemoveAt(0);
            foreach (var shop in Manager.Shops.Where(s => s.Name.ToLower().Contains(tb_search.Text.ToLower()))) lb_items.Items.Add(shop.Name);

            if (id!=null && !id.Equals("")) lb_items.SelectedItem = id;
            Mouse.OverrideCursor = null;
        }

        public bool Save_Context()
        {
            if (_actualPanel != null && _actualPanel.save_button.IsEnabled)
            {
                MessageBoxResult result = MessageBox.Show("Vuoi salvare il lavoro prima di procedere?", "Avviso",
                                                          MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
                        var resSave = _actualPanel.Save();
                        if (!resSave) _actualPanel.save_button.IsEnabled = false;
                        Refresh_Shop_List(_actualPanel.tb_nomeNegozio.Text);
                        if (!resSave) _actualPanel.save_button.IsEnabled = true;
                        Mouse.OverrideCursor = null;
                        break;
                    case MessageBoxResult.No:
                        break;
                    case MessageBoxResult.Cancel:
                        return false;
                }
            }
            return true;
            
        }

        void Close_Context()
        {
            if (_actualPanel != null && _actualPanel.save_button.IsEnabled)
            {
                MessageBoxResult result = MessageBox.Show("Vuoi salvare prima di chiudere?", "Avviso",
                                                          MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        _actualPanel.Save();
                        _actualPanel = null;
                        shopContentPane.Content = _actualPanel;
                        bt_cancella.IsEnabled = false;
                        lb_items.SelectedItem = null;
                        Refresh_Shop_List();
                        break;
                    case MessageBoxResult.No:
                        _actualPanel = null;
                        shopContentPane.Content = _actualPanel;
                        bt_cancella.IsEnabled = false;
                        lb_items.SelectedItem = null;
                        break;
                    case MessageBoxResult.Cancel:
                        break;
                }
            }
            else
            {
                _actualPanel = null;
                shopContentPane.Content = _actualPanel;
                bt_cancella.IsEnabled = false;
                lb_items.SelectedItem = null;
            }

        }

        public bool CheckShopOnDelete(string name)
        {
            IEnumerable<string> canDeleteMessage;

            var canDelete = Operations.CanRemoveShop(name, out canDeleteMessage);
            var msgFromCanRemove = canDeleteMessage.Aggregate("", (current, m) => current + (Environment.NewLine + m));
            var msgStr = "";


            if (canDelete)
            {
                msgStr += (string)Application.Current.FindResource("ElementCanBeDeleted");
                if (!msgFromCanRemove.Equals("")) msgStr += " " + (string)Application.Current.FindResource("ElementIsUsedBy") + msgFromCanRemove;

                var dresult = MessageBox.Show(msgStr, (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.YesNo, MessageBoxImage.Warning);

                switch (dresult)
                {
                    case MessageBoxResult.Yes:
                        return true;
                    case MessageBoxResult.No:
                        return false;
                }
            }
            else
            {
                msgStr = (string)Application.Current.FindResource("ElementCannotBeDeleted") + msgFromCanRemove;
                MessageBox.Show(msgStr, (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }

        #region ButtonHandlers

        public void Bt_Back_Click(object sender, RoutedEventArgs e)
        {
            if (!Save_Context()) return;
            Manager.ClearCache();
            Switcher.Switch(new MainMenu());
        }

        public void Bt_Add_Click(object sender, RoutedEventArgs e)
        {
            if (_actualPanel != null && !Save_Context()) return;
            _actualPanel = new ShopMainPane("");
            shopContentPane.Content = _actualPanel;
        }

        public void Bt_Search_Click(object sender, RoutedEventArgs e)
        {
            Refresh_Shop_List();
        }

        public void Bt_Clear_Search_Click(object sender, RoutedEventArgs e)
        {
            tb_search.Text = "";
            Refresh_Shop_List();
        }

        public void Bt_Delete_Click(object sender, RoutedEventArgs e)
        {
            if (CheckShopOnDelete((string)lb_items.SelectedValue))
            {
                Manager.Shops.Remove((string)lb_items.SelectedValue);
                Refresh_Shop_List();
                shopContentPane.Content = null;
                _actualPanel = null;
            }
          
        }

        public void Lb_Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Mouse.OverrideCursor= System.Windows.Input.Cursors.Wait;
            bt_cancella.IsEnabled = lb_items.SelectedItem != null;

            if (!Save_Context() || lb_items.SelectedValue == null)
            {
                Mouse.OverrideCursor = null;
                return;
            }
            _actualPanel = new ShopMainPane((string)lb_items.SelectedValue);
            shopContentPane.Content = _actualPanel;
            Mouse.OverrideCursor = null;
        }

        #endregion

        #region CloseCommandRegion

        readonly CommandBinding _closebinding = new CommandBinding(ApplicationCommands.Close, CommandCloseHandler);

        static void CommandCloseHandler(object target, ExecutedRoutedEventArgs e)
        {
            ((ShopUserControl)target).Close_Context();
            
        }

        #endregion

        #region SaveCommandRegion

        readonly CommandBinding _savebinding = new CommandBinding(ApplicationCommands.Save, CommandSaveHandler);

        static void CommandSaveHandler(object target, ExecutedRoutedEventArgs e)
        {
            var id = (string)((ShopUserControl)target).lb_items.SelectedItem;
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            ((ShopUserControl)target)._actualPanel.Save();
            ((ShopUserControl)target).Refresh_Shop_List(id);
            Mouse.OverrideCursor = null;
            
        }

        #endregion

        #region ISwitchable Members
        public void UtilizeState(object state)
        {
            throw new NotImplementedException();
        }
        #endregion

    }
}
